package com.aaa.mbs.service.impl;

import com.aaa.common.bo.Car;
import com.aaa.common.bo.Coupon;
import com.aaa.common.bo.CouponHistory;
import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnStatus;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.aaa.mbs.dao.MemberDao;
import com.aaa.mbs.dao.MemberLevelDao;
import com.aaa.mbs.dao.OrderDao;
import com.aaa.mbs.entity.*;
import com.aaa.mbs.service.*;
import com.aaa.mbs.util.SenderService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2020-12-05 14:23:59
 */
@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;
    /**
     * 依赖注入member服务 integrationHistoryService
     */
    @Resource
    private IntegrationHistoryService integrationHistoryService;
    @Resource
    private MemberLevelDao memberLevelDao;
    @Resource
    private MemberDao memberDao;
    /**
     * 依赖注入market服务 CouponHistoryService
     */
    @Autowired
    private RemoteCouponHistoryService couponHistoryService;
    /**
     * 依赖注入market服务 RemoteCouponService
     */
   /* @Autowired
    private RemoteCouponService remoteCouponService;*/

    /**
     * 依赖注入member服务 MemberLevelService
     */
    @Autowired
    private MemberLevelService memberLevelService;
    /**
     * 依赖注入member服务 MemberService
     */
    @Autowired
    private MemberService memberService;


    /**
     * 依赖注入member服务 AccountStatementService
     */
    @Autowired
    private AccountStatementService accountStatementService;

    /**
     * 依赖注入car服务 RemoteCarService
     */
    @Autowired
    private RemoteCarService remoteCarService;

    @Autowired
    private LocalMessageService localMessageService;

    @Autowired
    private SenderService senderService;

    /**
     * 按年月统计订单成交收入记录
     * @param yearMonth
     * @return
     */
    @Override
    public Result LoginLogShowByMonth(String yearMonth) {
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), this.orderDao.LoginLogShowByMonth (yearMonth));
    }
    @Override
    public void autoCanncelOrder() {
        //获取所有预定订单
        Order order = new Order ();
        order.setState (3);
        //获取所有预定订单
        List<Order> orders = orderDao.queryAll (order);
        //判断
        if (!CollectionUtils.isEmpty (orders)){
            Date nowDate = new Date ();
            //循环
            for (Order order1 : orders) {
                Date startTime = order1.getStartTime();
                //nowDate.getTime() 获取1970-1-1 午夜到现在的毫秒数
                if(nowDate.getTime()>startTime.getTime()){
                    //更新状态为取消状态
                    order1.setState(6);
                    orderDao.update(order1);
                }
            }
        }
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Order queryById(Integer id) {
        return this.orderDao.queryById (id);
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param pageNo
     * @param pageSize
     * @param order    实例对象
     * @return 对象列表
     */
    @Override
    public Result queryAll(int pageNo, int pageSize, Order order) {
        if (pageNo==0||pageSize==0){
            throw new CustomException (ExceptionConstant.INVALID_ARGUMENT.getErrorCode (),
                    ExceptionConstant.INVALID_ARGUMENT.getErrorMessage ());
        }
        //分页
        PageHelper.startPage (pageNo,pageSize);
        PageInfo<Order> pageInfo = new PageInfo<> (orderDao.queryAll (order));
        return new Result (ReturnStatus.SUCCESS.getReturnCode (),
                ReturnStatus.SUCCESS.getReturnMsg (),pageInfo);
    }

    @Override
    public Result queryAllMap(int pageNo, int pageSize, Map map) {
        if (pageNo==0||pageSize==0){
            throw new CustomException (ExceptionConstant.INVALID_ARGUMENT.getErrorCode (),
                    ExceptionConstant.INVALID_ARGUMENT.getErrorMessage ());
        }
        //分页
        PageHelper.startPage (pageNo,pageSize);
        PageInfo<Map> pageInfo = new PageInfo<> (orderDao.queryAllMap (map));
        return new Result (ReturnStatus.SUCCESS.getReturnCode (),
                ReturnStatus.SUCCESS.getReturnMsg (),pageInfo);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Order> queryAllByLimit(int offset, int limit) {
        return this.orderDao.queryAllByLimit (offset, limit);
    }

    /**
     * 新增数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public synchronized Order insert(Order order) {

        //获取当前下单用户的所有可用优惠券
/*        CouponHistory couponHistoryParam = new CouponHistory();
        couponHistoryParam.setCouponId(Long.valueOf(order.getBrrowShop()));
        couponHistoryParam.setMemberId(Long.valueOf(order.getClientId()));*/
        Integer memberId = order.getClientId();
        System.out.println("1-===============");
        System.out.println(order.getBrrowShop());
        System.out.println("2-===============");

        List<Coupon> couponList = couponHistoryService.getCouponListByMemberId(Long.valueOf(order.getBrrowShop()),
                Long.valueOf (memberId));
        //手机端计算的总价
        Double totalPrice = order.getTotalPrice();
        //定义优惠券总价钱
        Double totalCouponPrice = 0.0;
        //判断是否为空
        if(!CollectionUtils.isEmpty(couponList)){
            //循环遍历
            for (Coupon coupon : couponList) {
                totalCouponPrice+=coupon.getAmount();
                //设置优惠券使用数量加一
                coupon.setUseCount(coupon.getUseCount()+1);
                couponHistoryService.update(coupon);
                CouponHistory couponHistory  = new CouponHistory();
                couponHistory.setId(Long.valueOf(coupon.getHistoryCouponId()));
                couponHistory.setUseStatus(0);
                couponHistoryService.update(couponHistory);
            }
        }
        //设置实际支付金额
        double  payMoney =  totalPrice-totalCouponPrice;
        order.setTotalPrice(payMoney);
        //根据会员编号查询当前会员信息
        Member member = memberService.queryById(memberId);
        if(member!=null) {
            //根据实际消费金额更新成长值   实际消费金额和成长值 1:1
            double currentGrowth = member.getGrowth() + payMoney;
            member.setGrowth(currentGrowth);
            //获取会员等级列表
            Result result = memberLevelService.queryAlllist (1, 10, null);
            List<MemberLevel> memberLevelList =  ( List<MemberLevel>)result.getData();
            //定义消费后的会员等级ID 8000+3000 =11000  3
            long  growthLevelId = member.getMemberLevelId();
            //判断是否为空
            if(!CollectionUtils.isEmpty(memberLevelList)){
                for (MemberLevel memberLevel : memberLevelList) {
                    if(currentGrowth>=memberLevel.getGrowthPoint()){
                        growthLevelId = memberLevel.getId();
                        break;
                    }
                }
            }
            member.setMemberLevelId(Integer.valueOf(growthLevelId+""));
            //根据实际消费金额更新账户余额
            if((member.getAccountBalance()-payMoney)<0){
                new CustomException(ExceptionConstant.DATA_NOT_EXIST.getErrorCode(),ExceptionConstant.DATA_NOT_EXIST.getErrorMessage());
            }
            member.setAccountBalance(member.getAccountBalance() - payMoney);
            //根据会员ID获取会员等级
            MemberLevel memberLevel = memberLevelService.queryById(member.getMemberLevelId());
            Double ratio = 0.0;
            if(memberLevel!=null){
                ratio = memberLevel.getRatio();
            }
            //根据比率计算当前消费积分
            Double payIntegration  =  payMoney*ratio;
            //更新会员的当前积分和历史积分
            member.setIntegration(member.getIntegration()+new Double(payIntegration).intValue());
            member.setHistoryIntegration(member.getHistoryIntegration()+new Double(payIntegration).intValue());
            //向历史积分表插入数据
            IntegrationHistory integrationHistory = new IntegrationHistory();
            Date date = new Date();
            integrationHistory.setAddtime(date);
            integrationHistory.setChangeCount(payIntegration.intValue());
            integrationHistory.setChangeType(1);
            integrationHistory.setMemberId(memberId);
            integrationHistory.setOperateMan("admin");
            integrationHistory.setOperateNote("添加消费积分");
            integrationHistory.setSourceType(2);
            integrationHistory.setCreateTime(date);
            integrationHistoryService.insert(integrationHistory);
            //向会员账号流水表插入数据
            AccountStatement accountStatement = new AccountStatement();
            accountStatement.setAddtime(date);
            accountStatement.setAmount(payMoney);
            accountStatement.setClientId(memberId);
            accountStatement.setPayId(1);
            accountStatement.setTypeId(1);
            accountStatementService.insert(accountStatement);
            //修改车辆状态
            Car car =new Car();
            car.setId(order.getCarId());
            car.setState(3);
            String context = JSONObject.toJSONString(car);
            // 初始化本地消息为发送失败，mq回调确认收到消息后修改为发送成功
            //本地消息服务一般抽离出来做成一个本地消息服务系统，因为其他服务也会用到，也要进行实现最终一致性进行存储本地消息
            LocalMessage localMessage=new LocalMessage();
            localMessage.setContent(context);
            localMessage.setSerialNumber(UUID.randomUUID().toString());
            localMessage.setState(LocalMessage.L_M_STATE_FAIL);
            localMessageService.insert(localMessage);
            senderService.send(context,String.valueOf(localMessage.getId()));
//            remoteCarService.update(car);
            //调用更新方法
            memberService.update(member);
        }
        this.orderDao.insert(order);
        return order;
    }

    /**
     * 修改数据
     *
     * @param order 实例对象
     * @return 实例对象
     */
    @Override
    public Order update(Order order) {
        this.orderDao.update (order);
        return this.queryById (order.getId ());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.orderDao.deleteById (id) > 0;
    }

    /**
     * 下订单
     * @param member 会员对象
     * @param money 消费的金额
     * @return
     */
    @Override
    public Result memberOrder(Member member, Double money,Integer carId) {

            if (money<=0){
                throw new CustomException (ExceptionConstant.INVALID_ARGUMENT.getErrorCode (),
                        ExceptionConstant.INVALID_ARGUMENT.getErrorMessage ());
            }
           //获取会员id
           Integer  memberId= member.getId ();
           //账户余额
           Double  accountBalance= member.getAccountBalance ();
           //剩余账户余额
           Double consume = accountBalance-money;
           //添加积分流水
           IntegrationHistory integrationHistory= changecount (member,money);
           integrationHistoryService.insert (integrationHistory);
           //获取会员等级对象
           MemberLevel memberLevel =memberLevelDao.queryById (member.getMemberLevelId ()) ;
           //获取积分比率
        Double ratio=  memberLevel.getRatio ();
           //增加的积分
           int addpoints = (int) (money*ratio);
           //更改后的积分总额
           int integration = member.getIntegration () + addpoints;
           //更改后的历史总积分
           int integrations = member.getHistoryIntegration () + addpoints;
           //更改后的总成长值
        Double growth =  member.getGrowth () + money;
           member.setAccountBalance (consume);
           member.setIntegration (integration);
           member.setHistoryIntegration (integrations);
           member.setGrowth (growth);
           memberDao.update (member);
        return null;
    }

    /**
     * 增加积分封装方法
     * @param member
     * @return
     */
    @Override
    public IntegrationHistory changecount(Member member,Double money) {
        //获取会员id
        Integer  memberId= member.getId ();
        //获取会员名字
        String name= member.getName ();
        //获取会员等级对象
        MemberLevel memberLevel =memberLevelDao.queryById (member.getMemberLevelId ()) ;
        //获取积分比率
        Double ratio=  memberLevel.getRatio ();
        //增加的积分
        int addpoints = (int) (money*ratio);
        //获取积分对象
        IntegrationHistory integrationHistory=  new IntegrationHistory ();
        integrationHistory.setMemberId (memberId);
        integrationHistory.setChangeType (1);
        integrationHistory.setChangeCount (addpoints);
        integrationHistory.setOperateMan (name);
        integrationHistory.setOperateNote ("消费积分");
        integrationHistory.setSourceType (0);
        return integrationHistory;
    }
    /**
     * 会员等级自动变化
     * @return
     */
    @Override
    public void memberlevel() {
        //获取所有启用的会员
        Member member = new Member ();
        member.setStatus (1);
        List<Member> memberList= memberDao.queryAll (member);
        //获取会员等级对象
        MemberLevel memberLevel = new MemberLevel ();
        memberLevel.setPriviledgeComment (1);
        List<MemberLevel> memberLevels = memberLevelDao.queryAll (memberLevel);
        if (!CollectionUtils.isEmpty (memberList)){
            //遍历会员集合
            for (Member member1 : memberList) {
                //遍历会员等级集合
                for (MemberLevel level : memberLevels) {
                    //判断会员成长值大于会员等级成长值 则赋予相应的会员等级
                    if (member1.getGrowth () >= level.getGrowthPoint ()){
                        member1.setMemberLevelId (level.getId ());
                          memberDao.update (member1);
                          break;
                    }
                }

            }
        }

    }

    /**
     * 获取租出的，或者预约的所有汽车id    开始时间  结束时间
     * @return
     */
    @Override
    public Result queryByTime() {
        return new Result (ReturnStatus.SUCCESS.getReturnCode (),
                ReturnStatus.SUCCESS.getReturnMsg (),this.orderDao.queryByTime());
    }
}